#pragma once
#include "Common.hpp"
#include "Socket.hpp"
#include <memory>
#include <wait.h>
#include <functional>
using namespace SocketMoudule;
using ioservice_t = function<void(shared_ptr<Socket>&,InetAddr&)>;
class TcpServer
{
public:
    TcpServer(uint16_t port)
        : _port(port), _listensockptr(make_unique<TcpSocket>(port)), _isrunning(false)
    {
        _listensockptr->BuildTcpServerMoudule(_port);
    }
    void Start(ioservice_t callout)
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr client;
            auto sock = _listensockptr->Accept(&client);
            if (sock == nullptr)
            {
                LOG(Level::WARING) << "client accept fail";
                continue;
            }
            int id = fork();
            if (id < 0)
            {
                LOG(Level::FATAL) << "fork fail";
                exit(FORK_ERRO);
            }
            else if (id == 0)
            {
                _listensockptr->Close();
                if (fork() > 0)
                    exit(SUCCESS);
                callout(sock,client);
                exit(SUCCESS);
            }
            else
            {
                sock->Close();
                waitpid(id,nullptr,0);
            }
        }
    }

private:
    uint16_t _port;
    unique_ptr<Socket> _listensockptr;
    bool _isrunning;
};